package com.baofu.paycore.manager.storer.impl;

import com.baofu.paycore.common.enums.FlagEnum;
import com.baofu.paycore.common.enums.UpdateUser;
import com.baofu.paycore.common.exception.PayCoreBizException;
import com.baofu.paycore.dal.mapper.FreezeMapper;
import com.baofu.paycore.dal.model.FreezeDO;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.dal.model.SubTransferDO;
import com.baofu.paycore.dal.model.TransferDO;
import com.baofu.paycore.dal.model.base.BaseDO;
import com.baofu.paycore.manager.converter.BO2DOConverter;
import com.baofu.paycore.manager.converter.DO2BOConverter;
import com.baofu.paycore.manager.model.TransferBO;
import com.baofu.paycore.manager.storage.impl.SubTransferManager;
import com.baofu.paycore.manager.storage.impl.TransferManager;
import com.baofu.paycore.manager.storer.AbstractOrderRepository;
import com.baofu.paycore.manager.storer.TransferOrderRepository;
import com.baofu.paycore.service.facade.enums.PayStatusEnums;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.system.commons.utils.BeanCopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 转账订单
 *
 * <p/>
 *      1、查询主单信息
 * </p>
 * User: LZQ Date: 2016/04/20  Version: 1.0
 */
@Slf4j
@Repository
public class TransferOrderRepositoryImpl extends AbstractOrderRepository<TransferBO> implements TransferOrderRepository {

    /**
     * 转账
     */
    @Autowired
    private TransferManager transferManager;

    /**
     * 子转账
     */
    @Autowired
    private SubTransferManager subTransferManager;

    @Autowired
    private FreezeMapper freezeMapper;

    /**
     * 订单转换
     *
     * @param transferBO    支付对象
     * @return              转换后DO
     */
    @Override
    protected List<BaseDO> convertToDO(TransferBO transferBO) {
        TransferDO transferDO = BO2DOConverter.getTransferDO(transferBO);
        List<BaseDO> baseDOs = Lists.newArrayList(transferDO);
        baseDOs.addAll(transferBO.getSubTransferDO());
        return baseDOs;
    }

    /**
     * 加载并锁定订单
     *
     * @param requestOrderNo   请求订单号
     * @param requestBizNo     请求流水号
     * @return                 支付信息
     */
    @Override
    public TransferBO lock(String requestOrderNo, String requestBizNo,String requestSystem) {
        return null;
    }

    /**
     * 加载订单
     *
     * @param payNo 支付单号
     * @return 订单
     */
    @Override
    public TransferBO load(String payNo) {
        TransferDO transferDO = transferManager.getByPayNo(payNo);
        if (transferDO == null){
            log.error("查询转账主单信息为空 payNo:{}", payNo);
            throw new PayCoreBizException(PayCoreErrorCode.ORDER_IS_NOT_EXISTED);
        }
        List<SubTransferDO> lists = subTransferManager.selectByPayNo(payNo);

        return DO2BOConverter.buildTransferBO(transferDO, lists);
    }

    /**
     * 加载订单
     *
     * @param requestBizNo     请求流水号
     * @param requestOrderNo   请求订单号
     * @param requestSystem    请求系统
     * @return 订单
     */
    @Override
    public TransferBO load(String requestBizNo, String requestOrderNo,String requestSystem) {
        TransferDO transferDO = transferManager.selectByOrderNo(requestOrderNo,requestBizNo,requestSystem);
        if (transferDO == null){
            log.error("查询转账主单信息为空 requestBizNo:{},requestBizNo:{},requestSystem:{}",
                    requestBizNo,requestBizNo,requestSystem);
            throw new PayCoreBizException(PayCoreErrorCode.ORDER_IS_NOT_EXISTED);
        }
        List<SubTransferDO> lists = subTransferManager.selectByPayNo(transferDO.getPayNo());

        return DO2BOConverter.buildTransferBO(transferDO, lists);
    }

    @Override
    public void updateUnfreeze(TransferBO transferBO, long dealAmt) {
        TransferDO transferDO = BO2DOConverter.getTransferDO(transferBO);
        transferManager.modifyOrder(transferDO);
        List<SubTransferDO> subTransferDOS=transferBO.getSubTransferDO();
        if(subTransferDOS!=null&&subTransferDOS.size()>0){
            subTransferDOS.forEach(subTransferDO -> subTransferManager.modifyOrder(subTransferDO));
        }
        FreezeDO freezeDO=new FreezeDO();
        freezeDO.setPayNo(transferBO.getOldPayNo());
        freezeDO.setDealAmt(dealAmt);
        freezeMapper.updateDealAmt(freezeDO);
    }

    /**
     * 幂等性校验
     *
     * @param requestBizNo     请求流水号
     * @param requestOrderNo   请求订单号
     * @return                 订单
     */
    @Override
    public TransferBO checkIdempotent(String requestBizNo, String requestOrderNo,String requestSystem) {
        TransferDO transferDO = transferManager.selectByOrderNo(requestOrderNo,requestBizNo,requestSystem);
        return BeanCopyUtil.objConvert(transferDO,TransferBO.class);
    }

    /**
     * 更新撤销单及原单
     *
     * @param order         撤销订单
     */
    @Transactional
    public void updateCancelOrder(TransferBO order){
        TransferDO transferDO = new TransferDO();
        transferDO.setPayNo(order.getPayNo());
        transferDO.setStatus(order.getStatus());
        transferDO.setUpdatedBy(UpdateUser.SYS.getUserName());
        transferManager.modifyOrder(transferDO);
        subTransferManager.modifyOrder(order.getSubTransferDO().get(0));

        if(!Objects.equal(order.getStatus(), PayStatusEnums.FAIL.getCode())){

            TransferDO oldTransferDO = new TransferDO();
            oldTransferDO.setPayNo(order.getOldTransferBO().getPayNo());
            oldTransferDO.setCancelFlag(FlagEnum.TRUE.getCode());
            oldTransferDO.setUpdatedBy(UpdateUser.SYS.getUserName());
            transferManager.modifyOrder(oldTransferDO);
        }
    }
}
